#!/usr/bin/env bash
set -e

echo "=== Zsh 环境一键部署脚本（非 root 用户）==="

# 获取当前用户 HOME
USER_HOME="$HOME"
ZSH_CUSTOM="${ZSH_CUSTOM:-$USER_HOME/.oh-my-zsh/custom}"

# 检查包管理器
if command -v yum &> /dev/null; then
    PKG="yum"
elif command -v apt-get &> /dev/null; then
    PKG="apt-get"
else
    echo "[X] 不支持的系统（需要 yum 或 apt-get）"
    exit 1
fi

# 安装函数：不存在才安装
install_if_not_exist() {
    if ! command -v "$1" &> /dev/null; then
        echo "[+] 安装 $1"
        sudo $PKG install "$1" -y
    else
        echo "[✓] 已安装 $1"
    fi
}

# 安装必要软件
for pkg in git zsh wget curl tmux; do
    install_if_not_exist $pkg
done

# 推荐工具（自动跳转、文件搜索等）
# for extra in bat exa fd-find ripgrep fzf; do
#    install_if_not_exist $extra || true
# done

# 安装 pip3 和 thefuck（部分系统没有 python3-pip）
# if ! command -v pip3 &> /dev/null; then
#     sudo $PKG install python3-pip -y
# fi
# pip3 install --user thefuck

# 安装 autojump
if [ ! -d "$USER_HOME/.autojump" ]; then
    git clone https://github.com/wting/autojump.git "$USER_HOME/.autojump"
    cd "$USER_HOME/.autojump"
    ./install.py
    cd -
fi

# 安装 Oh-My-Zsh
if [ ! -d "$USER_HOME/.oh-my-zsh" ]; then
    echo "[+] 安装 Oh-My-Zsh"
#    sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended
    sh -c "$(curl -fsSL https://gitee.com/mirrors/oh-my-zsh/raw/master/tools/install.sh)" "" --unattended
fi

# 安装插件
git clone https://github.com/zsh-users/zsh-autosuggestions "$ZSH_CUSTOM/plugins/zsh-autosuggestions" || true
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git "$ZSH_CUSTOM/plugins/zsh-syntax-highlighting" || true
git clone --depth=1 https://github.com/romkatv/powerlevel10k.git "$ZSH_CUSTOM/themes/powerlevel10k" || true

# 下载配置文件
cp "$USER_HOME/.zshrc" "$USER_HOME/.zshrc.bak_$(date +%s)" 2>/dev/null || true
cat > "$USER_HOME/.zshrc" <<EOF
export ZSH="$USER_HOME/.oh-my-zsh"
ZSH_THEME="powerlevel10k/powerlevel10k"

plugins=(git zsh-autosuggestions zsh-syntax-highlighting autojump thefuck)

source \$ZSH/oh-my-zsh.sh

# 用户补全
[[ -f ~/.p10k.zsh ]] && source ~/.p10k.zsh

# FZF 配置
[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh

# The Fuck
eval "\$(thefuck --alias)"

# Autojump
[ -f ~/.autojump/etc/profile.d/autojump.sh ] && . ~/.autojump/etc/profile.d/autojump.sh
EOF

# 安装 Powerlevel10k 配置文件（可选）
if [ ! -f "$USER_HOME/.p10k.zsh" ]; then
    # curl -fsSL https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/config/p10k-classic.zsh -o "$USER_HOME/.p10k.zsh"
    wget https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/config/p10k-classic.zsh -O "$USER_HOME/.p10k.zsh"
fi

# 设置默认 shell 为 zsh
# if [ "$SHELL" != "/bin/zsh" ]; then
#    echo "[*] 设置默认 shell 为 zsh"
#    chsh -s /bin/zsh
# fi

echo -e "\n✅ 安装完成，请重新登录或手动执行 zsh 启动新的 shell 环境。"